#include "StdAfx.h"
#include "serialport.h"


serialport::serialport(void)
{
	portCom = CreateFile( "COM1",  
							GENERIC_READ | GENERIC_WRITE, 
							0, 
							0, 
							OPEN_EXISTING,
							FILE_FLAG_OVERLAPPED,
							0);
	if (portCom == INVALID_HANDLE_VALUE)
	{
		cout << "Nie mozna otworzyc portu COM1" << endl;
	}

	fWaitingOnRead = FALSE;

	FillMemory(&dcb, sizeof(dcb), 0);
	dcb.DCBlength = sizeof(dcb);
	if(!BuildCommDCB("baud=9600 parity=n data=8 stop=1", &dcb))
	{
		cout << "Problemy z ustawieniem parametrow portu COM1" << endl;
	}

	//timeouts.ReadIntervalTimeout = MAXDWORD; 
	timeouts.ReadTotalTimeoutMultiplier = 0;
	timeouts.ReadTotalTimeoutConstant = 10000;
	timeouts.WriteTotalTimeoutMultiplier = 0;
	timeouts.WriteTotalTimeoutConstant = 0;

	if (!SetCommTimeouts(portCom, &timeouts))
	{
		cout << "Nie udalo sie ustawic timeout-ow dla COM1" << endl;
	}
}

serialport::serialport(string _port)
{
	portCom = CreateFile( _port.c_str(),  
							GENERIC_READ | GENERIC_WRITE, 
							0, 
							0, 
							OPEN_EXISTING,
							FILE_ATTRIBUTE_NORMAL,
							0);
	if (portCom == INVALID_HANDLE_VALUE)
	{
		cout << "Nie mozna otworzyc portu" << _port << endl;
	}

	fWaitingOnRead = FALSE;

	FillMemory(&dcb, sizeof(dcb), 0);
	dcb.DCBlength = sizeof(dcb);
	if(!BuildCommDCB("baud=9600 parity=n data=8 stop=1", &dcb))
	{
		cout << "Problemy z ustawieniem parametrow portu" << _port << endl;
	}

	//timeouts.ReadIntervalTimeout = MAXDWORD; 
	timeouts.ReadTotalTimeoutMultiplier = 0;
	timeouts.ReadTotalTimeoutConstant = 10000;
	timeouts.WriteTotalTimeoutMultiplier = 0;
	timeouts.WriteTotalTimeoutConstant = 0;

	if (!SetCommTimeouts(portCom, &timeouts))
	{
		cout << "Nie udalo sie ustawic timeout-ow dla " << _port << endl;
	}
}




serialport::~serialport(void)
{
	CloseHandle(portCom);
}


BOOL serialport::writeABuffer(void* lpBuf, DWORD dwToWrite)
{
	if (!WriteFile(portCom, lpBuf, dwToWrite, &dwWritten, NULL))
	{
		
		if (GetLastError() != ERROR_IO_PENDING)
		{ 
			cout << "WriteFile failed" << endl;
			writeStatus = FALSE;
		}
		else 
		{
			cout << "Odczyt. Blad nr:" << GetLastError() << endl;
		}
	}
	else
	{
		writeStatus = TRUE;
	}

	return writeStatus;
}

BOOL serialport::readABuffer(void* lpBuf, DWORD dwToRead)
{
	
	if (!fWaitingOnRead)
	{
	   if (!ReadFile(portCom, lpBuf, dwToRead, &dwRead, NULL))
	   {
		  if (GetLastError() != ERROR_IO_PENDING)
		  {	
			  cout <<" Error in communications" << endl;
		  }
		  else
		  {
			 fWaitingOnRead = TRUE;
			 cout << "Zapis. Blad nr:" << GetLastError() << endl;
		  }

		  readStatus = FALSE;

	   }
	   else
	   {
		   readStatus = TRUE;
	   }
	}

	return readStatus;
}